/* eslint-disable import/no-extraneous-dependencies */
import { defineConfig, loadEnv } from 'vite';
import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import vue from '@vitejs/plugin-vue';
import styleImport from 'vite-plugin-style-import';
import legacy from '@vitejs/plugin-legacy';
import path from 'path';
import generateModifyVars from './build/generate/generateModifyVars';

// https://vitejs.dev/config/
export default ({ mode }) => {
  const { VITE_PROXY_URL, VITE_PORT, VITE_SOURCE_MAP } = loadEnv(mode, process.cwd());

  return defineConfig({
    build: {
      sourcemap: VITE_SOURCE_MAP === 'true' ? true : VITE_SOURCE_MAP as 'hidden' | 'inline',
    },
    plugins: [
      vue(),
      Components({
        dirs: ['src/components'],
        resolvers: [AntDesignVueResolver({
          importStyle: 'less',
          resolveIcons: true,
        })],
      }),
      styleImport({
        libs: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => `ant-design-vue/es/${name}/style/index.less`,
          },
        ],
      }),
      legacy({
        targets: ['ie >= 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: generateModifyVars(),
          javascriptEnabled: true,
        },
      },
    },
    server: {
      port: Number(VITE_PORT),
      proxy: {
        '/api': {
          target: VITE_PROXY_URL,
          changeOrigin: true,
          rewrite: (pPath) => pPath.replace(/^\/api/, ''),
        },
      },
    },
  });
};
